#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：Employment_class 
@File    ：07_MyWebserver.py
@IDE     ：PyCharm 
@Author  ：XiaoDengYa
@Date    ：2021/7/19/019 9:25 
"""
import re
import sys
from multiprocessing import Process
from socket import *

WSGI_PYTHON_DIR = "./wsgiPy"


class HTTPServer(object):
    def __init__(self, application):
        self.server_socket = socket(AF_INET, SOCK_STREAM)
        self.server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        self.app = application

    def start(self):
        self.server_socket.listen(128)
        while True:
            client_socket, client_addrs = self.server_socket.accept()
            print("【%s：%s】用户已经链接上了" % (client_socket, client_addrs))
            handle_client_pool = Process(target=self.handle_client, args=(client_socket,))
            handle_client_pool.start()
            client_socket.close()  # 因为客户端的socket已经通过进程传入给handle_client了，所以这个要关闭

    def start_response(self, status, headers):
        response_handers = "HTTP/1.1 " + status + "\r\n"
        for header in headers:
            response_handers += "%s: %s\r\n" % header  # 把请求头都放到response_handers中
        self.response_handers = response_handers

    def handle_client(self, client_socket):
        request_data = client_socket.recv(1024)
        print("request data:", request_data)
        request_liens = request_data.splitlines()
        for lien in request_liens:
            print(lien)

        # 解析请求报文 GET / HTTP/1.1
        request_start_line = request_liens[0]
        print("-" * 20)
        print(request_start_line.decode("utf-8"))
        filename = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).group(1)
        method = re.match(r"(\w+) +/[^ ]* ", request_start_line.decode("utf-8")).group(1)

        env = {"PATH_INFO": filename, "METHOD": method}
        response_body = self.app(env, self.start_response)

        response = self.response_handers + "\r\n" + response_body

        client_socket.send(bytes(response, "utf-8"))
        client_socket.close()

    def bind(self, prot):
        self.server_socket.bind(("", prot))


def main():
    sys.path.insert(1, WSGI_PYTHON_DIR)
    if len(sys.argv) < 2:
        exit("运行方式有误，如：python MyWebServer.py Module:app")

    module_name, appname = sys.argv[1].split(":")
    m = __import__(module_name)
    app = getattr(m, appname)
    httpserver = HTTPServer(app)
    httpserver.bind(7799)
    httpserver.start()


if __name__ == '__main__':
    main()
